package com.example.downloader.upload2;

import android.support.v4.util.SparseArrayCompat;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

class TaskQueue<R> {
    private final Map<String, Task<R>> mTaskQueue = new ConcurrentHashMap<>();
    private final SparseArrayCompat<Callback<R>> mTaskCallbacks = new SparseArrayCompat<>();

    void pushTask(String params, Task<R> task) {
        mTaskQueue.put(params, task);
    }

    void recordTaskCallback(Callback<R> callback) {
        mTaskCallbacks.append(callback.getId(), callback);
    }

    void popTask(String params) {
        mTaskQueue.remove(params);
    }

    private Callback<R> popTaskCallback(int id) {
        final int index = mTaskCallbacks.indexOfKey(id);
        if (index >= 0) {
            final Callback<R> callback = mTaskCallbacks.valueAt(index);
            mTaskCallbacks.removeAt(index);
            return callback;
        }
        return null;
    }

    Task<R> getTask(String path) {
        return mTaskQueue.get(path);
    }

    public void releaseCallback(int id) {
        final Callback<R> callback = popTaskCallback(id);
        if (callback != null) {
            final Task<R> task = callback.getTask();
            if (task != null) {
                task.removeCallback(callback);
                callback.detachTask();
            }
        }

    }


}
